# !/usr/bin/env python
# -*- coding: utf-8 -*-
# _author_ = "angusguo"

import psutil,os,time
from pwd import getpwnam

DiskUsage = psutil.disk_usage('/')
dir = {1:'/home/golanger/log/', 2:'/home/wwwroot/lnmp02/logs/', 3:'/home/wwwroot/lnmp04/logs/'}

def SelectedFile(FilePath):	
# 获取对应路径下文件名	
	FileNameList = os.listdir(FilePath)
	SelectedFileNameList = []
	for FileName in FileNameList:
		if FileName[:1] == '.':	# os.listdir方法会列出隐藏文件
			continue
		else:
			SelectedFileNameList.append(FileName)
	return SelectedFileNameList

def SwitchTime(Dir, FileName):
# 转换文件ctime
	os.chdir(Dir)
	FileTime = os.stat(FileName)
	os.chdir('/root/')
	TimeArray = time.localtime(FileTime.st_ctime)	# 先转换为数组再转换为需要的格式	
	TimeSwitched = time.strftime("%Y%m%d", TimeArray)
	return	TimeSwitched

def GetLocalTime():
# 获取本地时间
	Time = time.localtime(time.time())
	LocalTime = time.strftime("%Y%m%d", Time)
	return LocalTime

def GetUidGid(UserName):
# 获取账号UID GID
	name = getpwnam(UserName)
	return (name.pw_uid, name.pw_gid)

if DiskUsage.percent > 80:
	i = 1
	while i <= 3:
		f = dir.get(i)	# 取出目录名
		i += 1
		path = r'%s' %(f)
		if os.path.exists(path):	# 判断目录是否存在
			n = 0
			while n < len(SelectedFile(f)):	# 轮询所有文件名
				n += 1
				for NameList in SelectedFile(f):	# 取出文件名	
					if os.path.isfile(r'%s' %(f + NameList)):
						if SwitchTime(f, NameList) == GetLocalTime():
							os.chdir(f)
							file = open(NameList, 'w')
							file.truncate()
							file.close()
							if 'lnmp' in f:
								uid = GetUidGid('www')[0]
								gid = GetUidGid('www')[1]
								os.chown(NameList, uid, gid)
							else:
								uid = GetUidGid('golanger')[0]
								gid = GetUidGid('golanger')[1]
								os.chown(NameList, uid, gid)
							os.chdir('/root/')
						else:
							os.chdir(f)
							os.remove(NameList)
							os.chdir('/root/')
					else:
						SecPath = r'%s' %(f + NameList)
						path = f + NameList
						for name in SelectedFile(SecPath):
							if SwitchTime(path, name) == GetLocalTime():
								os.chdir(path)
								file = open(name, 'w')
								file.truncate()
								file.close()
								if 'lnmp' in path:
									uid = GetUidGid('www')[0]
									gid = GetUidGid('www')[1]
									os.chown(name, uid, gid)
								else:
									uid = GetUidGid('golanger')[0]
									gid = GetUidGid('golanger')[1]
									os.chown(name, uid, gid)
								os.chdir('/root/')
							else:
								os.chdir(path)
								os.remove(name)
								os.chdir('/root/')
